import { selectAppVersion } from '@/api/common.js';
import store from '../store/index.js';

/**
 * 展开树型结构数据
 * @param {Object} arr 需要展开的数组
 * @param {Object} key 子级的key，比如 children
 */
export const flatten = function (arr, key) {
  if (key) {
    return arr.reduce((result, item) => {
      if (item[key]) {
        result.push(item);
      }
      return result.concat(Array.isArray(item[key]) && item[key].length > 0 ? flatten(item[key], key) : item);
    }, []);
  } else {
    return arr.reduce((result, item) => {
      return result.concat(Array.isArray(item) && item[key].length > 0 ? flatten(item) : item);
    }, []);
  }
}

/**
 * 检测app是否需要升级
 * @param {Boolean}  isForce 是否强制查询
 * @param {Function}  callback 回调函数，会传入提示信息
 */
export const checkAppUpdate = async (isForce, callback) => {
	let checkUpdateKey = 'checkAppUpdate';
	let now = new Date();
  let today = `${now.getFullYear()}${now.getMonth() + 1}${now.getDate()}`;
	if (!store.state.vx_isChecked || store.state.vx_isChecked != today || isForce) {
    store.commit('$uStore', {
      name: 'vx_isChecked',
      value: today
    });
    try {
      const curVersion = plus.runtime.versionCode;
      // todo 请求接口
      // const res = await selectAppVersion();
      const res = {
        version: 140000,
        url: 'http://www.baidu.com'
      };
      if (curVersion < res.version) {
        uni.showModal({
          title: '更新提醒',
          content: '发现新的版本，请问是否更新？',
          success: e => {
            if (e.confirm) {
              plus.runtime.openURL(res.url);
            }
          }
        })
      } else {
        if (callback) {
        	callback('已是最新版本！');
        }
      }
    } catch(e) {
      console.log(e);
    }
	}
}